package com.wms.transport.proxys;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;

import com.wms.core.token.login.TokenLogin;

/**
 * 
 * 真正处理request的servlet（代理servlet）
 *
 */
public class Standard extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	private static final Logger logger = Logger.getLogger(Standard.class);
	
	private static WebApplicationContext  wac;
	
	private int code;
	
	public Standard(){
		super();
	}
	
	public static void setWac(WebApplicationContext wac) {
		Standard.wac = wac;
	}
	
	public void doRun(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		doPost(request,response);
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug("Proxy Standand : doGet");
		doPost(request,response);
	}
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		code = (TokenLogin.checkToken(request.getSession().getId()) == 0 ? 501 : 200);//判断token是否可用
		
		try{
			if(code == 501){
				throw new Exception("SESSION与服务器不一致");
			}
			
			logger.debug("Proxy Standand : 接收到的Bean Id是 :"+java.net.URLDecoder.decode(request.getParameter("type"),"UTF-8"));
			Object obj = wac.getBean(java.net.URLDecoder.decode(request.getParameter("type"),"UTF-8"));
			String resCont = (String) obj.getClass().getMethod("doRun",String.class).invoke(obj,java.net.URLDecoder.decode(request.getParameter("content"),"UTF-8"));
			
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setContentType("application/x-www-form-urlencoded");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter(); 
			
			out.print(resCont);//将json string 放入response的回复中
			out.flush();//response 发送
			
			logger.debug("返回结果 : "+resCont);
			logger.debug("response 处理完毕");
			
		}catch (Exception e) {
			
			e.printStackTrace();
			response.setStatus(code);
		} 
		
	}
	
	
	
	
	
}
